<!--  -->
<template>
  <div id="app_Userlist">
    <!------------------------------------------------ 头部----------------------------------------------- -->
    <div class="app_Userlist_top">
      <div class="app_Userlist_top_content">
        <section class="app_Userlist_top_head">
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button @click="clear">重置</el-button>
          <el-button type="primary" @click="searchuser">查询搜索</el-button>
        </section>
        <section class="app_Userlist_foot">
          <label style="width: 140px;">输入搜索：</label>
          <el-input
            v-model="input"
            placeholder="账号/姓名"
          ></el-input>
        </section>
      </div>
    </div>
    <!-- ----------------------------------------------中间------------------------------------------------- -->
    <div class="app_Userlist_center">
      <section class="app_Userlist_center_content">
        <i class="el-icon-tickets"></i>
        <span>数据列表</span>
        <el-button>添加</el-button>
      </section>
    </div>
    <!-- -----------------------------------------------底部 -------------------------------------------->
    <div class="app_Userlist_bottom">
      <div class="app_Userlist_bottom_content">
        <!-- 表格 -->
        <el-table
          :data="
            userlist.slice((currentPage - 1) * pageSize, currentPage * pageSize)
          "
          style="width: 100%"
        >
          <!-- 1 -->
          <el-table-column
            label="编号"
            align="center"
            type="index"
          >
          </el-table-column>
          <!-- 2 -->
          <el-table-column
            prop="account"
            label="账号"
            align="center"
          >
          </el-table-column>
          <!-- 3 -->
          <el-table-column
            prop="username"
            label="姓名"
            align="center"
          >
          </el-table-column>
          <!-- 4 -->
          <el-table-column
            prop="email"
            label="邮箱"
            align="center"
          >
          </el-table-column>
          <!-- 5 -->
          <el-table-column
            prop="authority"
            label="权限"
            align="center"
          >
          </el-table-column>
          <!-- 6 -->
          <el-table-column
            prop="logintiem"
            label="注册时间"
            align="center"
          >
          </el-table-column>
          <!-- 7 --> 
          <el-table-column
            prop="yeson"
            label="是否启用"
            align="center"
          >
            <template slot-scope="scope"><el-switch v-model="scope.row.on" 
            on-color="#00A854"
            on-text="启动"
            on-value="true"
            off-color="#F04134"
            off-text="禁止"
            off-value="false"> </el-switch></template>
          </el-table-column>
          <!-- 8 -->
          <el-table-column
            prop="option"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <div>
                <span>
                  <el-button
                    type="text"
                    @click="role(scope.row.username)"
                  ><a href="javascript:void(0);">分配角色</a></el-button>
                </span>
              </div>
              <div>
                <span>
                  <el-button
                    type="text"
                    @click="open"
                  ><a href="javascript:void(0);">编辑</a></el-button>
                  <el-button type="text"><a
                      href="javascript:void(0);"
                      @click="deleteuser(scope.row.account)"
                    >删除</a></el-button>
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- -------------------分页器 ------------------------------->
        <div
          class="block"
          style="margin:20px 0 50px 0; display:flex;justify-content: flex-end;"
        >
          <el-pagination
            align="center"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[ 5]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userlist.length"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-------------------------------------------------- 弹出窗--------------------------------------- -->
    <el-dialog
      title="分配角色"
      :visible.sync="allocDialogVisible"
      width="30%"
    >
      <el-select
        v-model="allocRoleIds"
        placeholder="请选择"
        size="small"
        style="width: 80%"
      >
        <el-option
          v-for="item in allRoleList"
          :key="item.id"
          :label="item.name"
          :value="item.name"
        >
        </el-option>
      </el-select>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="allocDialogVisible = false"
          size="small"
        >取 消</el-button>
        <el-button
          type="primary"
          @click="handleAllocDialogConfirm()"
          size="small"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import axios from "axios";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      /*------------------------------------- 表格------------------------------- */
      tableData: [],
      currentPage: 1, // 当前页码
      total: 20, // 总条数
      pageSize: 5, // 每页的数据条数
      /* ------------- */
      userlist: [],
      count: "",
      input: "",
      value: true,
      allocDialogVisible: false,
      allocUsername: "",
      allocRoleIds: "",
      allRoleList: [{ name: "超级管理员", id: "1" }, { name: "订单管理员", id: "2" }, { name: "商品管理员", id: "3" }, { name: "无权限用户", id: "4" }]

    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    /* -----------------------------------查询搜索------------------------------------------- */
    searchuser(){
      // key是搜索的关键字；后台接口也需要定义这个字段
      this.$axios.post("http://49.233.65.169:3000/api/queryuser",{ username: this.input })
      .then( res => {
        // 数据请求成功后的返回
       console.log(res); 
       this.userlist = res.result;
      })
      .catch(error => {
        // 请求错误的返回
        console.log(error);
      })
    },
    /*---------------------------------- 修改用户权限----------------------------------------------- */
    handleAllocDialogConfirm() {
      console.log(this.allocUsername, this.allocRoleIds);
      this.$axios
        .post("http://49.233.65.169:3000/api/change", {
          account: this.allocUsername,
          name: this.allocRoleIds
        }).then(res => {
          console.log(res);
          this.$message({
            message: '权限修改成功!',
            type: 'success'
          });
          this.allocDialogVisible = false;
          this.userlist.forEach((v, i) => {
            if (v.username === this.allocUsername) {
              this.userlist[i].authority = this.allocRoleIds
            }
          })
        }).catch(err => console.log(err))
    },
    /* -------------------------------------分页器 -------------------------------------------------------*/
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    /* --------------------------------------重置-------------------------------------------------------- */
    clear() {
      this.input = "";
    },
    /* ---------------------------------------编辑---------------------------------------------------------- */
    open() {
      this.$alert(
        '<textarea rows="8" cols="40" style="margin-left:40px"></textarea>',
        "编辑 :",
        {
          dangerouslyUseHTMLString: true,
        }
      );
    },
    /* --------------------------------------分配角色--------------------------------------------------------- */
    role(username) {
      this.allocUsername = username;
      this.allocDialogVisible = true
    },
    /* ----------------------------------------删除--------------------------------------------------------------- */
  deleteuser(account) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
         console.log(this);
         this.$axios
          .post("http://49.233.65.169:3000/api/deleteuser", {
            account: account,
          })
          .then( (response)=>{
            var arr= this.userlist.filter((v, i) => {
              console.log(v);
              return v.account!==account
            })
            this.userlist=arr;
             this.$message({
            message: '删除用户成功!',
            type: 'success'
          });
            return response.data;
          })
          .catch(function (error) {
            console.log(error);
          });
      });
    },
  },
  /* ======================================================================== */
  //生命周期 - 创建完成（可以访问当前this实例）

  //用户
  async created() {
    this.userlist = await axios
      .get("http://49.233.65.169:3000/api/userlist")
      .then((data) => {
        return data.data;
      });
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  /* -------------------------------查询搜索---------------------------- */
  mounted() {
   },
  beforeCreate() { }, //生命周期 - 创建之前
  beforeMount() { }, //生命周期 - 挂载之前
  beforeUpdate() { }, //生命周期 - 更新之前
  updated() { }, //生命周期 - 更新之后
  beforeDestroy() { }, //生命周期 - 销毁之前
  destroyed() { }, //生命周期 - 销毁完成
  activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="less" scoped>
/* ----------------------------头部--------------------------------- */
.user-msg-box {
  position: absolute;
  bottom: 50%;
  right: 50%;
}
#app_Userlist {
  margin: 20px;
  .app_Userlist_top {
    border: 1px solid #ebeef5;
    background-color: #fff;
    color: #303133;
    .app_Userlist_top_content {
      padding: 20px;
      .app_Userlist_top_head {
        i.el-icon-search {
        }
        span {
          margin-right: 895px;
          margin-left: 10px;
          font-size: 16px;
        }
        el-button {
        }
      }
      .app_Userlist_foot {
        margin-left: 50px;
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        width: 300px;
        label {
          text-align: center;
          line-height: 40px;
        }
      }
    }
  }
}
/* ----------------------------中间 ------------------------------*/
.app_Userlist_center {
  border: 1px solid #ebeef5;
  color: #303133;
  margin-top: 20px;
  .app_Userlist_center_content {
    padding: 20px;
    i.el-icon-tickets {
    }

    span {
      margin-right: 1000px;
      margin-left: 10px;
      font-size: 16px;
    }

    el-button {
    }
  }
}
/* ----------------------------底部 --------------------------------------*/
.app_Userlist_bottom {
  margin-top: 20px;
  .app_Userlist_bottom_content {
    border: 1px solid #ebeef5;
    div {
      span {
        a {
          text-decoration: none;
          color: #409eff;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
